package com.sjsu.aws.ephermeralnode;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import org.apache.log4j.Logger;
import com.sjsu.aws.doublebarrier.DoubleBarrierServiceImpl;

/**
 * 
 * @author Pawar Deepali
 * 
 */
public class DoubleBarrierEphemeralWatcher {
	private final static Logger	                  LOG	      = Logger.getLogger(DoubleBarrierEphemeralWatcher.class);
	
	private final static ScheduledExecutorService	scheduler	= Executors
	                                                                  .newScheduledThreadPool(1);
	
	public static void main(String[] args) throws Exception {
		long pollingPeriod = 10000;
		startPolling(pollingPeriod);
	}
	
	/**
	 * 
	 * @param pollingPeriod polling period in miliseconds
	 * @throws Exception
	 */
	public static void startPolling(long pollingPeriod) throws Exception {
		LOG.info("Start Polling for DoubleBarrier Ephemeral Watcher with pollingPeriod: "
		        + pollingPeriod);
		DoubleBarrierServiceImpl doubleBarrierServiceImpl = new DoubleBarrierServiceImpl();
		pollDB(pollingPeriod, doubleBarrierServiceImpl);
	}
	
	/**
	 * 
	 * @param pollingPeriod
	 * @param doubleBarrierServiceImpl
	 */
	public static void pollDB(long pollingPeriod,
	        final DoubleBarrierServiceImpl doubleBarrierServiceImpl) {
		final Runnable watcher = new Runnable() {
			public void run() {
				try {
					LOG.info("Deleting TimeOut Sessions For EphemeralNode  for DoubleBarrier");
					doubleBarrierServiceImpl
					        .deleteTimeOutSessionsForEphemeralNode();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		
		final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
		        watcher, 0, pollingPeriod, MILLISECONDS);
	}
}